using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using WeatherSystem.API.BackgroundJobs;
using WeatherSystem.API.Models;

namespace WeatherSystem.API.Controllers
{
    /// <summary>
    /// 后台作业管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize] // 需要身份验证
    public class JobsController : ControllerBase
    {
        private readonly IBackgroundJobService _jobService;
        private readonly ILogger<JobsController> _logger;

        public JobsController(IBackgroundJobService jobService, ILogger<JobsController> logger)
        {
            _jobService = jobService;
            _logger = logger;
        }

        /// <summary>
        /// 立即执行数据采集作业
        /// </summary>
        [HttpPost("data-collection")]
        [Authorize(Policy = "UserOrAdmin")]
        public async Task<IActionResult> TriggerDataCollection()
        {
            try
            {
                var jobId = await _jobService.EnqueueDataCollectionAsync();
                return Ok(new { JobId = jobId, Message = "数据采集作业已启动" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发数据采集作业失败");
                return StatusCode(500, new { Message = "启动数据采集作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 执行特定城市的数据采集
        /// </summary>
        [HttpPost("data-collection/city/{cityId:guid}")]
        [Authorize(Policy = "UserOrAdmin")]
        public async Task<IActionResult> TriggerCityDataCollection(Guid cityId)
        {
            try
            {
                var jobId = await _jobService.EnqueueCityDataCollectionAsync(cityId);
                return Ok(new { JobId = jobId, CityId = cityId, Message = "城市数据采集作业已启动" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发城市数据采集作业失败，城市ID: {CityId}", cityId);
                return StatusCode(500, new { Message = "启动城市数据采集作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 执行统计生成作业
        /// </summary>
        [HttpPost("statistics-generation")]
        [Authorize(Policy = "UserOrAdmin")]
        public async Task<IActionResult> TriggerStatisticsGeneration()
        {
            try
            {
                var jobId = await _jobService.EnqueueStatisticsGenerationAsync();
                return Ok(new { JobId = jobId, Message = "统计生成作业已启动" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发统计生成作业失败");
                return StatusCode(500, new { Message = "启动统计生成作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 执行数据清理作业
        /// </summary>
        [HttpPost("data-cleanup")]
        [Authorize(Policy = "AdminOnly")]
        public async Task<IActionResult> TriggerDataCleanup()
        {
            try
            {
                var jobId = await _jobService.EnqueueDataCleanupAsync();
                return Ok(new { JobId = jobId, Message = "数据清理作业已启动" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发数据清理作业失败");
                return StatusCode(500, new { Message = "启动数据清理作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 生成天气报告
        /// </summary>
        [HttpPost("weather-report")]
        [Authorize(Policy = "UserOrAdmin")]
        public async Task<IActionResult> GenerateWeatherReport([FromBody] WeatherReportRequest request)
        {
            try
            {
                if (request.StartDate >= request.EndDate)
                {
                    return BadRequest(new { Message = "开始时间必须小于结束时间" });
                }

                if ((request.EndDate - request.StartDate).Days > 90)
                {
                    return BadRequest(new { Message = "时间范围不能超过90天" });
                }

                var jobId = await _jobService.EnqueueWeatherReportGenerationAsync(
                    request.CityId, request.StartDate, request.EndDate);
                
                return Ok(new 
                { 
                    JobId = jobId, 
                    CityId = request.CityId,
                    StartDate = request.StartDate,
                    EndDate = request.EndDate,
                    Message = "天气报告生成作业已启动" 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发天气报告生成作业失败");
                return StatusCode(500, new { Message = "启动天气报告生成作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 批量模拟数据生成
        /// </summary>
        [HttpPost("bulk-simulation")]
        [Authorize(Policy = "AdminOnly")]
        public async Task<IActionResult> TriggerBulkDataSimulation([FromBody] BulkSimulationRequest request)
        {
            try
            {
                if (request.RecordsPerCity <= 0 || request.RecordsPerCity > 1000)
                {
                    return BadRequest(new { Message = "每城市记录数必须在1-1000之间" });
                }

                var jobId = await _jobService.EnqueueBulkDataSimulationAsync(
                    request.RecordsPerCity, request.BaseTemperature);
                
                return Ok(new 
                { 
                    JobId = jobId, 
                    RecordsPerCity = request.RecordsPerCity,
                    BaseTemperature = request.BaseTemperature,
                    Message = "批量数据模拟作业已启动" 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发批量数据模拟作业失败");
                return StatusCode(500, new { Message = "启动批量数据模拟作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 执行缓存预热作业
        /// </summary>
        [HttpPost("cache-warmup")]
        [Authorize(Policy = "AdminOnly")]
        public async Task<IActionResult> TriggerCacheWarmup()
        {
            try
            {
                var jobId = await _jobService.EnqueueCacheWarmupAsync();
                return Ok(new { JobId = jobId, Message = "缓存预热作业已启动" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "触发缓存预热作业失败");
                return StatusCode(500, new { Message = "启动缓存预热作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 获取作业状态
        /// </summary>
        [HttpGet("status/{jobId}")]
        [Authorize(Policy = "ReadOnlyOrHigher")]
        public async Task<IActionResult> GetJobStatus(string jobId)
        {
            try
            {
                var status = await _jobService.GetJobStatusAsync(jobId);
                return Ok(status);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取作业状态失败，作业ID: {JobId}", jobId);
                return StatusCode(500, new { Message = "获取作业状态失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 取消作业
        /// </summary>
        [HttpDelete("{jobId}")]
        [Authorize(Policy = "UserOrAdmin")]
        public async Task<IActionResult> CancelJob(string jobId)
        {
            try
            {
                var result = await _jobService.CancelJobAsync(jobId);
                if (result)
                {
                    return Ok(new { JobId = jobId, Message = "作业取消成功" });
                }
                else
                {
                    return NotFound(new { JobId = jobId, Message = "作业未找到或无法取消" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "取消作业失败，作业ID: {JobId}", jobId);
                return StatusCode(500, new { Message = "取消作业失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 获取作业统计信息
        /// </summary>
        [HttpGet("statistics")]
        [Authorize(Policy = "ReadOnlyOrHigher")]
        public async Task<IActionResult> GetJobStatistics()
        {
            try
            {
                var statistics = await _jobService.GetJobStatisticsAsync();
                return Ok(statistics);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取作业统计信息失败");
                return StatusCode(500, new { Message = "获取作业统计信息失败", Error = ex.Message });
            }
        }

        /// <summary>
        /// 设置定期作业（仅限管理员）
        /// </summary>
        [HttpPost("setup-recurring")]
        [Authorize(Policy = "AdminOnly")]
        public IActionResult SetupRecurringJobs()
        {
            try
            {
                _jobService.SetupRecurringJobs();
                return Ok(new { Message = "定期作业设置成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置定期作业失败");
                return StatusCode(500, new { Message = "设置定期作业失败", Error = ex.Message });
            }
        }
    }

    /// <summary>
    /// 天气报告生成请求
    /// </summary>
    public class WeatherReportRequest
    {
        public Guid CityId { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

    /// <summary>
    /// 批量数据模拟请求
    /// </summary>
    public class BulkSimulationRequest
    {
        public int RecordsPerCity { get; set; } = 10;
        public double BaseTemperature { get; set; } = 20.0;
    }
}